package com.heima.media.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.MediaThreadLocalUtil;
import com.heima.media.dto.*;
import com.heima.media.entity.WmNews;
import com.heima.media.entity.WmNewsMaterial;
import com.heima.media.entity.WmUser;
import com.heima.media.mapper.WmNewsMapper;
import com.heima.media.service.IAuditService;
import com.heima.media.service.IWmNewsMaterialService;
import com.heima.media.service.IWmNewsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.media.service.IWmUserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import springfox.documentation.spring.web.json.Json;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 自媒体图文内容信息表 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-21
 */
@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements IWmNewsService {
    @Autowired
    IWmUserService wmUserService;


    @Override
    public ResponseResult findPageByName(NewsAuthDto dto) {
        // 构建分页条件
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());
        // 构建查询条件
        LambdaQueryWrapper<WmNews> query = new LambdaQueryWrapper<>();
        // 根据标题模糊查询
        if (!StringUtils.isEmpty(dto.getTitle())) {
            query.like(WmNews::getTitle, dto.getTitle());
        }
        // 根据状态查询
        if (dto.getStatus() != null) {
            query.eq(WmNews::getStatus, dto.getStatus());
        }
        // 根据发布时间倒序排列
        query.orderByDesc(WmNews::getPublishTime);
        // 分页查询
        IPage<WmNews> iPage = this.page(page, query);
        List<WmNews> newsList = iPage.getRecords();
        List<WmNewsVo> vos=new ArrayList<>();
        for (WmNews wmNews : newsList) {
            WmNewsVo vo=new WmNewsVo();
            BeanUtils.copyProperties(wmNews,vo);
            WmUser user = wmUserService.getById(wmNews.getUserId());
            vo.setAuthorName(user.getName());
            vos.add(vo);
        }
        PageResponseResult result=new PageResponseResult(dto.getPage(),dto.getSize(),iPage.getTotal(),vos);

        return result;
    }

    @Override
    public ResponseResult findNewsVoById(Integer id) {
        // 根据id查询文章
        WmNews wmNews = this.getById(id);
        // 查询作者名称
        WmUser wmUser = wmUserService.getById(wmNews.getUserId());
        // 构建vo对象
        WmNewsVo vo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews, vo);
        vo.setAuthorName(wmUser.getName());
        // 通用响应
        return ResponseResult.okResult(vo);
    }

    /**
     * 内容分页
     * @param newsPageDto
     * @return
     */
    @Override
    public ResponseResult listByCondition(WmNewsPageDto newsPageDto) {
        IPage<WmNews> page=new Page<>(newsPageDto.getPage(),newsPageDto.getSize());
        LambdaQueryWrapper<WmNews> query=new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(newsPageDto.getStatus())){
            query.eq(WmNews::getStatus,newsPageDto.getStatus());
        }
        if(!StringUtils.isEmpty(newsPageDto.getChannelId())){
            query.eq(WmNews::getChannelId,newsPageDto.getChannelId());
        }
        if(!StringUtils.isEmpty(newsPageDto.getKeyword())){
            query.like(WmNews::getTitle,newsPageDto.getKeyword());
        }
        if(!StringUtils.isEmpty(newsPageDto.getBeginPubDate())){
            query.ge(WmNews::getPublishTime,newsPageDto.getBeginPubDate());
        }
        if(!StringUtils.isEmpty(newsPageDto.getEndPubDate())){
            query.lt(WmNews::getSubmitedTime,newsPageDto.getEndPubDate());
        }
        User user = MediaThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        query.eq(WmNews::getUserId,user.getUserId());
        query.orderByDesc(WmNews::getPublishTime);

        IPage<WmNews> ipage = this.page(page, query);
        ResponseResult result=new PageResponseResult(newsPageDto.getPage(),newsPageDto.getSize(),ipage.getTotal(),ipage.getRecords());
        return result;
    }


    @Autowired
    @Lazy    // 解决循环依赖问题
    private IAuditService auditService;

    @Override
    public ResponseResult submit(WmNewsDto dto) {
        User user = MediaThreadLocalUtil.get();
        if(user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //判断dto中有没有id
        //有的话他就是在更新文章需要删除已有文章-素材关联关系
        if(dto.getId()!=null){
            deleteRelation(dto.getId());
        }
        WmNews news=new WmNews();
        BeanUtils.copyProperties(dto,news);
        news.setUserId(user.getUserId());
        news.setCreatedTime(new Date());
        news.setSubmitedTime(new Date());
        news.setImages(JSON.toJSONString(dto.getImages()));
        //从内容中提取图片
        List<ImageDto> contentImages=getImagesFromContent(news.getContent());
        if(dto.getType()==-1){
            if(contentImages.size()<=0){
                //修改类型为无图
                news.setType(0);
            }else if(contentImages.size()<3){
                //修改类型为单图
                news.setType(1);
                List<ImageDto> dtos = contentImages.subList(0, 1);
                news.setImages(JSON.toJSONString(contentImages));
            }else{
                news.setType(3);
                List<ImageDto> imageDtos = contentImages.subList(0, 3);
                news.setImages(JSON.toJSONString(imageDtos));
            }
        }
//       this.save(news);
        this.saveOrUpdate(news);
       if(dto.getStatus()!=0){
           //不为草稿保存文章素材关联
           //添加封面关联
           List<ImageDto> imageDtos = JSON.parseArray(news.getImages(),ImageDto.class);
           saveRelation(imageDtos,news.getId(),1);
           //添加内容关联
           saveRelation(imageDtos,news.getId(),0);
           // 开始自动审核文章  需要异步处理
           System.out.println(Thread.currentThread().getName() + " 开始调用自动审核服务...");
           auditService.aduit(news);

       }
        return ResponseResult.okResult();
    }
    @Autowired
    private KafkaTemplate<String,String> kafkaTemplate;

    @Value("${topic.upDownTopic}")
    private String upDownTopic;
    /**
     * 下架、上架
     * @param dto
     * @return
     */
    @Override
    public ResponseResult downOrUp(WmNewsDto dto) {
        //根据id查询文章
        WmNews wmNews = this.getById(dto.getId());
        //判断
        if(wmNews==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        if(wmNews.getStatus()!=9){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        wmNews.setEnable(dto.getEnable()==0?false:true);
        this.updateById(wmNews);
        //同步到状态daoapp端
        kafkaTemplate.send(upDownTopic,wmNews.getArticleId().toString(),dto.getEnable()==1?"true":"false");
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult auth(NewsAuthDto dto, int type) {
        //根据文章id查询
        WmNews news = this.getById(dto.getId());
        if(type==1){
            news.setStatus(4);
            this.updateById(news);
            //发布文章
            auditService.aduit(news);
        }else{
            news.setStatus(2);
            news.setReason(dto.getMsg());
            this.updateById(news);
        }
        return ResponseResult.okResult();
    }

    /**
     * 删除文章素材关联
     * @param id
     */
    private void deleteRelation(Integer id) {
        LambdaQueryWrapper<WmNewsMaterial> query=new LambdaQueryWrapper<>();
        query.eq(WmNewsMaterial::getNewsId,id);
        newsMaterialService.remove(query);
    }

    /**
     * 提取图片
     * @param content
     * @return
     */
    private List<ImageDto> getImagesFromContent(String content) {
        List<ImageDto> contentImages=new ArrayList<>();
        List<ContentDto> contentDtos = JSON.parseArray(content, ContentDto.class);
        for (ContentDto contentDto : contentDtos) {
            if(contentDto.getType().equals("image")){
                String url = contentDto.getValue();
                Integer id = contentDto.getId();
                    ImageDto imageDto=new ImageDto(id,url);
                    contentImages.add(imageDto);
            }
        }
        return contentImages;
    }
    @Autowired
    private IWmNewsMaterialService newsMaterialService;


    /**
     * 保存关联关系
     *
     * @param images
     * @param newsId
     * @param type
     */
    private void saveRelation(List<ImageDto> images, Integer newsId, int type) {
        int ord = 0;
        for (ImageDto dto : images) {
            WmNewsMaterial entity = new WmNewsMaterial();
            entity.setMaterialId(dto.getId());
            entity.setNewsId(newsId);
            entity.setType(type);
            entity.setOrd(ord);
            newsMaterialService.save(entity);
            ord++;
        }
    }


}
